package com.tskj.mh.badminton.utility;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;

/**
 * 工具类，主要提供一些常用或通用的方法，比如servlet的响应结果，使用post方式调用别的servlet，从request中获取数据体内容等等
 * 不定期更新
 * getRequestJson、sendRespone、sendPostRequest
 *
 * @author LeonSu
 * @version 1.0
 * @date 2018-09-26
 */
@Component
public class Tools {
    public static JSONObject createEmptyData() {
        JSONObject retData = new JSONObject();
        retData.put("code", 0);
        retData.put("data", "[]");
        retData.put("list", "[]");
        return retData;
    }

    // 加密
    // 判断Key是否为16位
    //SUYAXUAN的今易加密
    private static final String LEONSU_KEY = "971F3E1DE50F8007";

    public static String Encrypt(String sSrc) throws Exception {
        return sSrc;
//        byte[] raw = LEONSU_KEY.getBytes("utf-8");
//        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//        //"算法/模式/补码方式"
//        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
//        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
//        //此处使用BASE64做转码功能，同时能起到2次加密的作用。
//        //return new Base64().encodeToString(encrypted);
//        return Base64.getEncoder().encodeToString(encrypted);
    }


    /**
     * 两个日期间相差的天数  这里不包含起始日期，如果想要结果包含起始日期，则需要再结果上+1
     *
     * @return
     */
    public static int getDifferenceDayCount(String startDateStr, String endDateStr) {

        LocalDate startDate = LocalDate.parse(startDateStr);
        LocalDate endDate = LocalDate.parse(endDateStr);
        //取正数
        return Math.abs((int) (endDate.toEpochDay() - startDate.toEpochDay()));
    }

    public static int countDaysInMonth() {
        // 获取当前时间
        LocalDate now = LocalDate.now();
        return now.lengthOfMonth();
        // 把当前时间的月份修改为输入的月份
//        LocalDate thisMonthDate = now.withMonth(month.getValue());
//        return thisMonthDate.lengthOfMonth();
    }

    public static String newFileName() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
    }

    /**
     * 按“yyyyMMddHHmmssSS”的格式生成一个字符串
     *
     * @return
     */
    public static String getNewDateTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    public static String getNowTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    }

    public static String getDate() {
        return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String getDate(int addDays) {
        return LocalDate.now().plusDays(addDays).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String getAddDate(LocalDateTime startDate, int addDays) {
        return startDate.plusDays(addDays).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String getAddDate(String startDate, int addDays) {
        LocalDateTime date = LocalDateTime.parse(startDate + "T23:59:59");
        return date.plusDays(addDays).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String getDate(LocalDate date, int addDays) {
        return date.plusDays(addDays).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    public static String getShortTime(String time) {
        return LocalTime.parse(time).format(DateTimeFormatter.ofPattern("HH:mm"));
    }

    public static String today() {
        return getDate();
    }

    public static String yesterday() {
        return getDate(-1);
    }

    public static String newId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取文件扩展名，不包括.
     *
     * @return
     */
    public static String ext(String filename) {
        int index = filename.lastIndexOf(".");

        if (index == -1) {
            return null;
        }
        return filename.substring(index + 1);
    }

    /**
     * @Author:vic
     * @Date:14:59 2018/11/30
     * @Description: is_desc-false升序列  is_desc-true降序 (排序字段为字符串)
     */
    public static JSONArray jsonArraySort(JSONArray jsonArr, String sortKey, boolean is_desc) {
        List<JSONObject> jsonValues;// = new ArrayList<>();
        jsonValues = jsonArr.toJavaList(JSONObject.class);
//        for (int i = 0; i < jsonArr.size(); i++) {
//            jsonValues.add(jsonArr.getJSONObject(i));
//        }
        jsonValues.sort(new Comparator<JSONObject>() {
            private final String KEY_NAME = sortKey;

            @Override
            public int compare(JSONObject a, JSONObject b) {

//                String valA = new String();
//                String valB = new String();
                try {
                    String valA = a.getString(KEY_NAME);
                    String valB = b.getString(KEY_NAME);
                    return is_desc ? -valA.compareToIgnoreCase(valB) : valA.compareToIgnoreCase(valB);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return 0;
//                if (is_desc) {
//                    return -valA.compareTo(valB);
//                } else {
//                    return -valB.compareTo(valA);
//                }

            }
        });
//        for (int i = 0; i < jsonArr.size(); i++) {
//            sortedJsonArray.add(jsonValues.get(i));
//        }
        JSONArray sortedJsonArray = new JSONArray();
        sortedJsonArray.addAll(jsonValues);
        return sortedJsonArray;
    }

    /**
     * 采用post方式，utf-8编码调用别的servlet，并返回utf-8编码的处理结果
     *
     * @param url，servlet的地址，不需要包含主机
     * @param jsonText
     * @return
     */
    public static String sendPostRequest(String url, String jsonText) {
        return sendPostRequest(url, jsonText, "");
    }

    public static String sendPostRequest(String url, String jsonText, String sessionId) {
        JSONObject jsonSend = new JSONObject();
        URL url1 = null;
        try {
            url1 = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            jsonSend.put("code", 1);
            jsonSend.put("errMsg", e.getMessage());
            return jsonSend.toString();
            //return "{}";
        }
        //System.out.println(url1.getHost());
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
            httpPost.setHeader(HTTP.CONTENT_ENCODING, "UTF-8");
            StringEntity se = new StringEntity(jsonText, "utf-8");
            se.setContentEncoding("UTF-8");
            httpPost.setEntity(se);
            HttpResponse httpResponse = client.execute(httpPost);
            if (httpResponse != null) {
                System.out.println(httpResponse.getStatusLine().getStatusCode());
            }
            if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
                HttpEntity entity = httpResponse.getEntity();
                StringBuilder result = new StringBuilder();
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String s;
                while (((s = reader.readLine()) != null)) {
                    result.append(s);
                }
                reader.close();
                return result.toString();
            } else {
                jsonSend.put("code", 1);
                jsonSend.put("errMsg", "连接状态码" + httpResponse.getStatusLine().getStatusCode());
                return jsonSend.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
            jsonSend.put("code", 1);
            jsonSend.put("errMsg", e.getMessage());
            return jsonSend.toString();
        }
    }
}
